<template>
  <div class="sections-page">
    <div class="page-header">
      <h2>板块列表</h2>
      <button @click="showCreateSectionModal" class="btn create-btn" v-if="currentUser">
        创建新板块
      </button>
    </div>

    <div class="sections-container" v-if="sections.length > 0">
      <div 
        class="section-card" 
        v-for="section in sections" 
        :key="section.section_id"
        @click="goToSection(section.section_id)"
      >
        <h3>{{ section.name }}</h3>
        <p v-if="section.description">{{ section.description }}</p>
        <div class="section-meta">
          <span>创建时间: {{ section.created_at || '未知' }}</span>
        </div>
      </div>
    </div>

    <div class="no-sections" v-else>
      <p>暂无板块，请创建第一个板块</p>
    </div>

    <!-- 创建板块模态框 -->
    <div class="modal-overlay" v-if="showSectionModal" @click="closeSectionModal">
      <div class="modal-container" @click.stop>
        <div class="modal-header">
          <h2>创建新板块</h2>
          <span class="close" @click="closeSectionModal">&times;</span>
        </div>
        <div class="modal-body">
          <form @submit.prevent="createSection" class="section-form">
            <div class="form-group">
              <label for="sectionName">板块名称</label>
              <input 
                type="text" 
                id="sectionName" 
                v-model="newSection.name" 
                required
                placeholder="请输入板块名称"
                class="form-input">
            </div>
            <div class="form-group">
              <label for="sectionDescription">板块描述</label>
              <textarea 
                id="sectionDescription" 
                v-model="newSection.description" 
                placeholder="请输入板块描述（可选）"
                class="form-textarea">
              </textarea>
            </div>
            <div class="form-actions">
              <button type="submit" class="submit-btn">创建</button>
              <button type="button" @click="closeSectionModal" class="cancel-btn">取消</button>
            </div>
          </form>
          <Alert 
            v-if="sectionMessage"
            :type="sectionMessageType"
            :description="sectionMessage"
            :closable="false"
            v-model="sectionAlertVisible"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Alert from '@/components/Alert.vue';

export default {
  name: 'Sections',
  components: {
    Alert
  },
  data() {
    return {
      sections: [],
      currentUser: null,
      showSectionModal: false,
      newSection: {
        name: '',
        description: ''
      },
      sectionMessage: '',
      sectionMessageType: '',
      sectionAlertVisible: true
    }
  },
  mounted() {
    this.loadSections();
    this.checkLoginStatus();
  },
  methods: {
    checkLoginStatus() {
      const user = localStorage.getItem('user');
      if (user) {
        this.currentUser = JSON.parse(user);
      }
    },
    async loadSections() {
      try {
        const response = await fetch('http://127.0.0.1:11451/sections/');
        if (response.ok) {
          this.sections = await response.json();
        }
      } catch (error) {
        console.error('加载板块列表失败:', error);
      }
    },
    showCreateSectionModal() {
      if (!this.currentUser) {
        alert('请先登录');
        this.$eventBus.emit('open-login');
        return;
      }
      this.showSectionModal = true;
      this.newSection = {
        name: '',
        description: ''
      };
      this.sectionMessage = '';
      this.sectionMessageType = '';
      this.sectionAlertVisible = true;
    },
    closeSectionModal() {
      this.showSectionModal = false;
    },
    async createSection() {
      try {
        const response = await fetch('http://127.0.0.1:11451/sections/', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(this.newSection)
        });

        if (response.ok) {
          const section = await response.json();
          this.sections.unshift(section); // 将新板块添加到列表开头
          this.sectionMessage = '板块创建成功';
          this.sectionMessageType = 'success';
          this.sectionAlertVisible = true;
          
          // 1秒后关闭模态框
          setTimeout(() => {
            this.closeSectionModal();
            this.newSection.name = '';
            this.newSection.description = '';
          }, 1000);
        } else {
          const error = await response.json();
          this.sectionMessage = error.detail || '创建板块失败';
          this.sectionMessageType = 'error';
          this.sectionAlertVisible = true;
        }
      } catch (error) {
        this.sectionMessage = '创建板块过程中发生错误: ' + error.message;
        this.sectionMessageType = 'error';
        this.sectionAlertVisible = true;
      }
    },
    goToSection(sectionId) {
      this.$router.push(`/section/${sectionId}`);
    }
  }
}
</script>

<style scoped>
.sections-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.create-btn {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.create-btn:hover {
  background-color: #0056b3;
}

.sections-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.section-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 20px;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.section-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.section-card h3 {
  margin: 0 0 10px 0;
  color: #007bff;
}

.section-card p {
  color: #666;
  margin-bottom: 15px;
  font-size: 14px;
}

.section-meta {
  font-size: 12px;
  color: #999;
}

.no-sections {
  text-align: center;
  padding: 50px 0;
  color: #666;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-container {
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  width: 90%;
  max-width: 500px;
  overflow: hidden;
  animation: modalFadeIn 0.3s ease-out;
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-header {
  padding: 20px;
  background: linear-gradient(135deg, #007bff, #0056b3);
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h2 {
  margin: 0;
  font-size: 1.5rem;
}

.close {
  color: white;
  font-size: 28px;
  font-weight: bold;
  cursor: pointer;
  transition: transform 0.2s;
}

.close:hover {
  transform: scale(1.1);
}

.modal-body {
  padding: 25px;
}

.section-form {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #333;
}

.form-input, .form-textarea {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
  box-sizing: border-box;
  transition: border-color 0.3s, box-shadow 0.3s;
}

.form-textarea {
  min-height: 100px;
  resize: vertical;
}

.form-input:focus, .form-textarea:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.submit-btn, .cancel-btn {
  flex: 1;
  padding: 12px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 600;
  transition: transform 0.2s, box-shadow 0.2s;
}

.submit-btn {
  background-color: #007bff;
  color: white;
}

.submit-btn:hover {
  background-color: #0056b3;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.cancel-btn {
  background-color: #6c757d;
  color: white;
}

.cancel-btn:hover {
  background-color: #545b62;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.message {
  padding: 12px;
  border-radius: 6px;
  margin-top: 15px;
  text-align: center;
  font-weight: 500;
}

.message.success {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.message.error {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

@media (max-width: 768px) {
  .sections-page {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .sections-container {
    grid-template-columns: 1fr;
  }
}
</style>
